import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
declare let Wechat;
@Injectable()
export class WechatService {

    /**
     * * 分享到朋友圈
     * @param scene 0 发给朋友，1分享到朋友圈
     * @param {string} id
     * @param {link: string; thumb: string; shortName: string; description: string} data
     * @param {any} success
     * @param {any} error
     */
    share(scene,id:string = 'send-link-thumb-remote',
          data?:{link:string,thumb?:string,shortName:string,description:string},
          success = null,error = null
          ) {
        if(typeof Wechat === 'undefined')return;
        let params:any = {
            scene: scene
        };
        data.description = data.description.length < 16 ? data.description:data.description.slice(0,16);
        data.shortName = data.shortName.length < 6 ? data.shortName:data.shortName.slice(0,6);
        params.message = {
            title:data.shortName,
            description: data.description,
            thumb:data.thumb,
            media: {
                type:Wechat.Type.WEBPAGE,
                webpageUrl:data.link
            }
        };
        Wechat.share(params,success,error);
    }

    isInstalled(){
        return Observable.create(observer => {
            if(typeof Wechat !== 'undefined'){
                Wechat.isInstalled( installed =>{
                    installed.flag = 1;
                    observer.next(installed);
                }, reason => {
                    const error = {
                        flag:0,
                        reason
                    };
                    observer.next(error);
                });
            }else{
                const error = {
                    flag:0,
                    reason:"微信未安装"
                };
                observer.next(error);
            }
        });
    }

}
